package my_wget;

require Exporter;


our @ISA = qw(Exporter);
our $VERSION = 1.00;
our @EXPORT = qw(ftp_get_file_if_newer);

use strict;
use warnings;
use Net::FTP;



#_________________________________________________________________________________________

#	ftp_get_file_if_newer($$$$\@$)

#		Input:

#			$remote_path_file		file to download
#			$local_date				file must be more recent than this
#			$local_path_temp_file	where to save downloaded file to

#_________________________________________________________________________________________
sub ftp_get_file_if_newer($\$$)
{
	# get remote file date
	my ($remote_path_file,
		$local_date,
		$local_path_temp_file) = @_;

	(my $host		 = $remote_path_file) =~ s[([^/]+).*][$1];
	(my $remote_file = $remote_path_file) =~ s[.*/][];
	(my $remote_path = $remote_path_file) =~ s[[^/]+(.*)/.*][$1];;


	my $ftp = Net::FTP->new($host, Debug =>0);
#	$ftp->pasv();
	die "$@" unless ($ftp);
	$ftp->login();
	$ftp->binary();
	$ftp->cwd($remote_path);
	
	my $remote_date = $ftp->mdtm($remote_file);
	

	my $remote_size = $ftp->size($remote_file);

	print STDERR  ">",scalar localtime($$local_date), "\n", scalar localtime($remote_date),"\n";
	return 2 if ($remote_date && $$local_date && $$local_date >= $remote_date);
	
	# get file
	my $rc = $ftp->get($remote_file, $local_path_temp_file);
	return "Error:\n\tFailed to download the file $remote_file to $local_path_temp_file\n$!\n"
		unless $rc && -f ($local_path_temp_file);

	my $local_size = (stat($local_path_temp_file))[7];
	if (!$local_size || ($remote_size && $local_size != $remote_size))
	{
		unlink $local_path_temp_file;
		return "Error:\nDownloaded file [$local_path_temp_file] was the wrong size\n".
		"(" . 				format_number($local_size),
		" instead of ".		format_number($remote_size). "\n";
	}
	$$local_date = $remote_date;
	
	return 1;	
}






